package com.demo.common.config;

import com.demo.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 读取项目相关配置
 */
public class GlobalConfig {
  /**
   * 项目名称
   */
  private String name;

  /**
   * 版本
   */
  private String version;

  /**
   * 版权年份
   */
  private String copyrightYear;

  /**
   * 上传路径
   */
  private static String profile;

  public String toString() {
    return "<pre><h1>" + this.name + "\r\n" + this.version + "\r\n" + this.copyrightYear
        + "\r\n" + DateUtils.dateTimeNow("yyyy/MM/dd HH:mm:ss") +
        "\r\n" + getAddress() +
        "\r\n" + getHostName() +
        "\r\n" + getMac()
        + "</h1>"
        + "</pre>";
  }

  public String getAddress() {
    try {
      InetAddress address = InetAddress.getLocalHost();
      return address.getHostAddress();
    } catch (UnknownHostException e) {
      // 异常或无权访问设置为 127.0.0.1
      e.printStackTrace();
      return "127.0.0.1";
    }
  }

  public String getHostName() {
    try {
      InetAddress address = InetAddress.getLocalHost();
      return address.getHostName();
    } catch (UnknownHostException e) {
      // 异常或无权访问设置为 localhost
      e.printStackTrace();
      return "localhost";
    }
  }

  public static String getMac() {
    try {
      InetAddress inetAddress = InetAddress.getLocalHost();
      byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "\n"));
      }
      return sb.toString();
    } catch (UnknownHostException | SocketException e) {
      // 异常或无权访问设置为 localhost
      e.printStackTrace();
      return "00-00-00-00-00-00";
    }
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getVersion() {
    return version;
  }

  public void setVersion(String version) {
    this.version = version;
  }

  public String getCopyrightYear() {
    return copyrightYear;
  }

  public void setCopyrightYear(String copyrightYear) {
    this.copyrightYear = copyrightYear;
  }

  public static String getProfile() {
    return profile;
  }

  public void setProfile(String profile) {
    GlobalConfig.profile = profile;
  }


  /**
   * 获取下载路径
   */
  public static String getDownloadPath() {
    return getProfile() + "/download/";
  }

  /**
   * 获取上传路径
   */
  public static String getUploadPath() {
    return getProfile() + "/upload";
  }
}
